package com.hospital.Common;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import com.hospital.activity.R;
import com.hospital.tools.SoapHelper;
import com.hospital.xml.HosHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.parsers.SAXParserFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通过POST GET 上传下载图片
 * Created by wangjun on 2015/6/8.
 */
public class NetUtil {

    // 图片加载
    private static ImageLoader IMAGE_LOADER;
    // 图片缓存包
    private static DisplayImageOptions LOAD_IMAGE;
    final public static String CONNECTION_URL = "http://www.kingtang.com/";

    // 检查网络状态
    public static boolean isNetworkAvailable(Activity activity) {
        Context context = activity.getApplicationContext();
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
            return false;
        } else {// 获取所有网络连接信息
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {// 逐一查找状态为已连接的网络
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static DisplayImageOptions getLOAD_IMAGE() {
        if (LOAD_IMAGE == null) {
            LOAD_IMAGE = new DisplayImageOptions.Builder()
                    .showStubImage(R.drawable.bianjijianlitouxiang) // 设置图片在下载期间显示的图片
                    .showImageForEmptyUri(R.drawable.bianjijianlitouxiang) // 设置图片Uri为空或是错误的时候显示的图片
                    .showImageOnFail(R.drawable.bianjijianlitouxiang) // 设置图片加载/解码过程中错误时候显示的图片
                    .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
                    .cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
                    .bitmapConfig(Bitmap.Config.RGB_565)
                    .displayer(new RoundedBitmapDisplayer(5)).build();
        }
        return LOAD_IMAGE;
    }

    public static final String IMAGES = "com.nostra13.example.universalimageloader.IMAGES";
    public static final String IMAGE_POSITION = "com.nostra13.example.universalimageloader.IMAGE_POSITION";

    public static ImageLoader getIMAGE_LOADER(Context context) {
        if (IMAGE_LOADER == null) {
            IMAGE_LOADER = ImageLoader.getInstance();
        }
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
        IMAGE_LOADER.init(config);
        return IMAGE_LOADER;
    }

    //发送Http请求
    public static void HttpPostData(String url, Map<String, Object> param,
                                    HttpAsyncCallback callback) {
        HttpRunnable httpRunnable = new HttpRunnable(CONNECTION_URL + url, param, callback);
//		Log.v("请求的url", CommonBean.CONNECTION_URL+url);
//		for(String key: param.keySet()){
//			Log.v("传入的参数------->"+key, String.valueOf(param.get(key)));
//		}
        new Thread(httpRunnable).start();
    }
    public  static  void SoapWsProcessRunnable(String xml,  HashMap<String ,String> in,
                                               HttpAsyncXmlCallBack callback){

        SoapWsProcessRunnable soapWsProcessRunnable=new SoapWsProcessRunnable(xml,in,callback);
        new Thread(soapWsProcessRunnable).start();

    }
    //发送图片请求
    public static void HttpPostPic(String url, File file,
                                   HttpAsyncCallback callback) {
        HttpPostPic httpRunnable = new HttpPostPic(file, CONNECTION_URL + url, callback);
//			Log.v("请求的url", CommonBean.CONNECTION_URL+url);
//			for(String key: param.keySet()){
//				Log.v("传入的参数------->"+key, String.valueOf(param.get(key)));
//			}
        new Thread(httpRunnable).start();
    }

    //发送Http请求
    public static void HttpGetData(String url,
                                   HttpAsyncCallback callback) {
        HttpGetRunnable httpRunnable = new HttpGetRunnable(CONNECTION_URL + url, callback);
        Log.i("请求的url", CONNECTION_URL + url);
        new Thread(httpRunnable).start();
    }
}

class HttpRunnable implements Runnable {
    public String url;
    public Map<String, Object> param;
    public HttpAsyncCallback callback;

    public HttpRunnable(String url, Map<String, Object> param,
                        HttpAsyncCallback callback) {
        this.url = url;
        this.param = param;
        this.callback = callback;
    }

    @Override
    public void run() {
        JSONObject jsonObject = null;
        HttpClient client = new DefaultHttpClient();
        StringBuilder builder = new StringBuilder();
        HttpPost myPost = new HttpPost(url);
        //  myPost.setHeader("Authorization", Constant.token);
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            if (param != null && !param.isEmpty()) {
                for (String key : param.keySet()) {
                    params.add(new BasicNameValuePair(key, String.valueOf(param
                            .get(key))));
                }
                // 发出HTTP request
                myPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            }
            // 设置连接的时间 20秒
            client.getParams().setParameter(
                    CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 数据传输时间60s
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                    60000);
            HttpResponse response = client.execute(myPost);
            // 判断请求是否成功
            System.out.println("回来的的状态" + response.getStatusLine().getStatusCode());
            //if (response.getStatusLine().getStatusCode() == 200||response.getStatusLine().getStatusCode() == 400) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            for (String s = reader.readLine(); s != null; s = reader
                    .readLine()) {
                builder.append(s);
            }
            jsonObject = new JSONObject(builder.toString());
            jsonObject.put("isNo", "0");
            System.out.println("回来的的" + jsonObject.toString());
            //}
        } catch (HttpHostConnectException e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "服务器连接异常");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } catch (ConnectTimeoutException e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "服务器连接超时");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "系统异常");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
//		Log.v("----------------------------->", jsonObject.toString());
        if(callback != null)
            callback.onSuccess(jsonObject);
    }
}

class  SoapWsProcessRunnable  implements  Runnable{
    public  String xml;
    public   HashMap<String ,String> in;
    public   List<HashMap<String,String>> entrys;

    public HttpAsyncXmlCallBack callback;
    public SoapWsProcessRunnable(String xml,  HashMap<String ,String> in,
                                 HttpAsyncXmlCallBack callback) {
        this.xml = xml;
        this.in = in;
        this.callback = callback;
    }
    @Override
    public void run() {
        InputStream ret=new SoapHelper().getXmlStream(xml, "Serviceprocessing");
//        BufferedReader reader = new BufferedReader(
//                new InputStreamReader(ret));
//        StringBuilder builder = new StringBuilder();
//        try{
//        for (String s = reader.readLine(); s != null; s = reader.readLine()) {
//            builder.append(s);
//        }
//        }catch (Exception e){
//
//
//        }
//        Log.i("11111111111",builder.toString());
        List<HashMap<String,String>> entrys=null;
        entrys=new ArrayList<HashMap<String,String>>(0);
        entrys.add(in);
        parse(ret, entrys);
        callback.onSuccess(entrys);
    }

    public void parse(InputStream ret,List<HashMap<String,String>> entrys){



        SAXParserFactory factory=SAXParserFactory.newInstance();

        try {
            XMLReader reader=factory.newSAXParser().getXMLReader();
            //解析////////////////////////////////////////////
            reader.setContentHandler(new HosHandler(entrys));
            reader.parse(new InputSource(ret));

        } catch (Exception e) {

        }
    }
}


class HttpGetRunnable implements Runnable {
    public String url;
    public Map<String, Object> param;
    public HttpAsyncCallback callback;

    public HttpGetRunnable(String url, Map<String, Object> param,
                           HttpAsyncCallback callback) {
        this.url = url;
        this.param = param;
        this.callback = callback;
    }

    public HttpGetRunnable(String url,
                           HttpAsyncCallback callback) {
        this.url = url;
        this.callback = callback;
    }

    @Override
    public void run() {
        JSONObject jsonObject = null;
        HttpClient client = new DefaultHttpClient();
        StringBuilder builder = new StringBuilder();
        HttpGet
                myPost = new HttpGet(url);
        //  myPost.setHeader("authorization", Constant.token);
        try {
//				List<NameValuePair> params = new ArrayList<NameValuePair>();
//				if (param != null && !param.isEmpty()) {
//					for (String key : param.keySet()) {
//						params.add(new BasicNameValuePair(key, String.valueOf(param
//								.get(key))));
//					}
//					// 发出HTTP request
//					myPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
//				}
            // 设置连接的时间 20秒
            client.getParams().setParameter(
                    CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
            // 数据传输时间60s
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                    60000);
            HttpResponse response = client.execute(myPost);
            // 判断请求是否成功
            if (response.getStatusLine().getStatusCode() == 200) {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                for (String s = reader.readLine(); s != null; s = reader
                        .readLine()) {
                    builder.append(s);
                }
                jsonObject = new JSONObject(builder.toString());
                jsonObject.put("isNo", "0");
                System.out.println("get返回的数据:" + jsonObject.toString());
            }
        } catch (HttpHostConnectException e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "服务器连接异常");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } catch (ConnectTimeoutException e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "服务器连接超时");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        } catch (Exception e) {
            try {
                jsonObject = new JSONObject();
                jsonObject.put("isNo", "-1");
                jsonObject.put("msg", "系统异常");
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
//			Log.v("----------------------------->", jsonObject.toString());
        callback.onSuccess(jsonObject);
    }
}

class HttpPostPic implements Runnable {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    private File file;
    private String url1;
    public HttpAsyncCallback callback;

    public HttpPostPic(File file, String url, HttpAsyncCallback callback) {
        this.file = file;
        this.url1 = url;
        this.callback = callback;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            URL url = new URL(url1);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
              /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
	          /* 设置传送的method=POST */
            con.setRequestMethod("POST");
	          /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
	          /* 设置DataOutputStream */
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " +
                    "name=\"file1\";filename=\"" +
                    "touxiang.jpg" + "\"" + end);
            ds.writeBytes(end);
	          /* 取得文件的FileInputStream */
            FileInputStream fStream = new FileInputStream(file);
	          /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
	          /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
	            /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
            }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
	          /* close streams */
            fStream.close();
            ds.flush();
	          /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            callback.onSuccess(new JSONObject(b.toString()));
	          /* 将Response显示于Dialog */

	          /* 关闭DataOutputStream */
            ds.close();
        } catch (Exception e) {
            System.out.println("出错了" + e);
            System.out.println("出错了");
        }
    }
}





